/**
 * 
 */
package com.smzd.framework.utils.freemarker.resolvers;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerView;

/**
 * @author YuZhongda
 *
 */
public class BaseFreeMarkerView extends FreeMarkerView {
	private static final String _SORT_ORDER = "_sort_order_";
	private static final String _SORT_NAME = "_sort_name_";
	private static final String PAGE_QUERY = "pagequery";
	private static final String PAGE_URI = "pageuri";
	private static final String CONTEXT_PATH = "base";

	@Override
	protected void exposeHelpers(Map<String, Object> model, HttpServletRequest request) throws Exception {
		String base = request.getContextPath();
		if (base == null || base.length() == 1) {
			base = "";
		}
		model.put(CONTEXT_PATH, base);
		String pageuri = request.getRequestURI();
		if (pageuri == null) {
			pageuri = "";
		}
		if (base.length() > 0 && pageuri.startsWith(base)) {
			pageuri = pageuri.replaceFirst(base, "");
		}
		if (pageuri.startsWith("/")) {
			pageuri = pageuri.substring(1);
		}
		model.put(PAGE_URI, pageuri);
		String queryString = request.getQueryString();
		if (StringUtils.isEmpty(queryString)) {
			queryString = null;
		} else {
			StringTokenizer st = new StringTokenizer(queryString, "&");
			List<String> params = new ArrayList<>();
			while (st.hasMoreTokens()) {
				String pairs = st.nextToken();
				String key = pairs.substring(0, pairs.indexOf('='));
				if ("p".equals(key)) {
					continue;
				}
				if ("sortName".equals(key)) {
					String value = pairs.substring(pairs.indexOf('=') + 1);
					model.put(_SORT_NAME, value);
					continue;
				}
				if ("sortOrder".equals(key)) {
					String value = pairs.substring(pairs.indexOf('=') + 1);
					model.put(_SORT_ORDER, value);
					continue;
				}
				params.add(pairs);
			}
			if (params.size() > 0) {
				queryString = "?" + StringUtils.join(params, "&");
			} else {
				queryString = null;
			}
		}

		model.put(PAGE_QUERY, queryString);
	}

}
